﻿#region Using References

using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;

#endregion

namespace Beaker.OpenCube.Dynamic
{
	/// <summary>
	/// Dictionary that keeps all values in a <see cref="WeakReference" /> so they
	/// can be released if nothing is referencing the data anymore
	/// </summary>
	/// <typeparam name="TKey">Type of the key in the dictionary.</typeparam>
	/// <typeparam name="TValue">Type of the value in the dictionary.</typeparam>
	public sealed class WeakDictionary<TKey, TValue>
		: IDictionary<TKey, TValue>
		where TValue : class
	{
		/// <summary>
		/// Actual dicitionary with the weak references
		/// </summary>
		private readonly Dictionary<TKey, WeakReference<TValue>> _dictionary
			= new Dictionary<TKey, WeakReference<TValue>>();

		#region Implementation of IEnumerable

		/// <summary>
		/// Returns an enumerator that iterates through the collection.
		/// </summary>
		/// <returns>
		/// A <see cref="T:System.Collections.Generic.IEnumerator`1" /> that can be used to iterate through the collection.
		/// </returns>
		IEnumerator<KeyValuePair<TKey, TValue>> IEnumerable<KeyValuePair<TKey, TValue>>.GetEnumerator()
		{
			var deletableKeys = new List<TKey>();

			foreach( KeyValuePair<TKey, WeakReference<TValue>> wkv in _dictionary )
			{
				TValue value;
				if( wkv.Value.TryGetTarget( out value ) )
					yield return new KeyValuePair<TKey, TValue>( wkv.Key, value );
				else
					deletableKeys.Add( wkv.Key );
			}

			foreach( TKey key in deletableKeys )
				_dictionary.Remove( key );
		}

		/// <summary>
		/// Returns an enumerator that iterates through a collection.
		/// </summary>
		/// <returns>
		/// An <see cref="T:System.Collections.IEnumerator" /> object that can be used to iterate through the collection.
		/// </returns>
		IEnumerator IEnumerable.GetEnumerator()
		{
			return ( (IEnumerable<KeyValuePair<TKey, TValue>>)this ).GetEnumerator();
		}

		#endregion

		#region Implementation of ICollection<KeyValuePair<TKey,TValue>>

		/// <summary>
		/// Adds an item to the <see cref="T:System.Collections.Generic.ICollection`1" />.
		/// </summary>
		/// <param name="item">The object to add to the <see cref="T:System.Collections.Generic.ICollection`1" />.</param>
		/// <exception cref="T:System.NotSupportedException">The <see cref="T:System.Collections.Generic.ICollection`1" /> is read-only.</exception>
		void ICollection<KeyValuePair<TKey, TValue>>.Add( KeyValuePair<TKey, TValue> item )
		{
			if( item.Value == null )
				throw new ArgumentNullException( "item" );

			Add( item.Key, item.Value );
		}

		/// <summary>
		/// Removes all items from the <see cref="T:System.Collections.Generic.ICollection`1" />.
		/// </summary>
		/// <exception cref="T:System.NotSupportedException">The <see cref="T:System.Collections.Generic.ICollection`1" /> is read-only.</exception>
		void ICollection<KeyValuePair<TKey, TValue>>.Clear()
		{
			_dictionary.Clear();
		}

		/// <summary>
		/// Determines whether the <see cref="T:System.Collections.Generic.ICollection`1" /> contains a specific value.
		/// </summary>
		/// <param name="item">The object to locate in the <see cref="T:System.Collections.Generic.ICollection`1" />.</param>
		/// <returns>
		/// true if <paramref name="item" /> is found in the <see cref="T:System.Collections.Generic.ICollection`1" />; otherwise, false.
		/// </returns>
		bool ICollection<KeyValuePair<TKey, TValue>>.Contains( KeyValuePair<TKey, TValue> item )
		{
			EqualityComparer<TKey> keyCompare = EqualityComparer<TKey>.Default;
			EqualityComparer<TValue> valCompare = EqualityComparer<TValue>.Default;

			return this
				.Any( kv =>
					keyCompare.Equals( kv.Key, item.Key )
					&& valCompare.Equals( kv.Value, item.Value )
				);
		}

		/// <summary>
		/// Copies the elements of the <see cref="T:System.Collections.Generic.ICollection`1" /> to an <see cref="T:System.Array" />, starting at a particular <see cref="T:System.Array" /> index.
		/// </summary>
		/// <param name="array">The one-dimensional <see cref="T:System.Array" /> that is the destination of the elements copied from <see cref="T:System.Collections.Generic.ICollection`1" />. The <see cref="T:System.Array" /> must have zero-based indexing.</param>
		/// <param name="arrayIndex">The zero-based index in <paramref name="array" /> at which copying begins.</param>
		/// <exception cref="T:System.ArgumentNullException"><paramref name="array" /> is null.</exception>
		/// <exception cref="T:System.ArgumentOutOfRangeException"><paramref name="arrayIndex" /> is less than 0.</exception>
		/// <exception cref="T:System.ArgumentException">The number of elements in the source <see cref="T:System.Collections.Generic.ICollection`1" /> is greater than the available space from <paramref name="arrayIndex" /> to the end of the destination <paramref name="array" />.</exception>
		void ICollection<KeyValuePair<TKey, TValue>>.CopyTo( KeyValuePair<TKey, TValue>[] array, int arrayIndex )
		{
			this
				.ToArray()
				.CopyTo( array, arrayIndex );
		}

		/// <summary>
		/// Removes the first occurrence of a specific object from the <see cref="T:System.Collections.Generic.ICollection`1" />.
		/// </summary>
		/// <param name="item">The object to remove from the <see cref="T:System.Collections.Generic.ICollection`1" />.</param>
		/// <returns>
		/// true if <paramref name="item" /> was successfully removed from the <see cref="T:System.Collections.Generic.ICollection`1" />; otherwise, false. This method also returns false if <paramref name="item" /> is not found in the original <see cref="T:System.Collections.Generic.ICollection`1" />.
		/// </returns>
		/// <exception cref="T:System.NotSupportedException">The <see cref="T:System.Collections.Generic.ICollection`1" /> is read-only.</exception>
		bool ICollection<KeyValuePair<TKey, TValue>>.Remove( KeyValuePair<TKey, TValue> item )
		{
			return _dictionary.Remove( item.Key );
		}

		/// <summary>
		/// Gets the number of elements contained in the <see cref="T:System.Collections.Generic.ICollection`1"/>.
		/// </summary>
		/// <returns>
		/// The number of elements contained in the <see cref="T:System.Collections.Generic.ICollection`1"/>.
		/// </returns>
		public int Count
		{
			get
			{
				// count via enumerator so gc'ed items are removed from count
				int i = 0;
				foreach( KeyValuePair<TKey, TValue> item in this )
					i++;
				return i;
			}
		}

		/// <summary>
		/// Gets a value indicating whether the <see cref="T:System.Collections.Generic.ICollection`1"/> is read-only.
		/// </summary>
		/// <returns>
		/// true if the <see cref="T:System.Collections.Generic.ICollection`1"/> is read-only; otherwise, false.
		/// </returns>
		bool ICollection<KeyValuePair<TKey, TValue>>.IsReadOnly
		{
			get { return false; }
		}

		#endregion

		#region Implementation of IDictionary<TKey,TValue>

		/// <summary>
		/// Determines whether the <see cref="T:System.Collections.Generic.IDictionary`2"/> contains an element with the specified key.
		/// </summary>
		/// <returns>
		/// true if the <see cref="T:System.Collections.Generic.IDictionary`2"/> contains an element with the key; otherwise, false.
		/// </returns>
		/// <param name="key">The key to locate in the <see cref="T:System.Collections.Generic.IDictionary`2"/>.</param><exception cref="T:System.ArgumentNullException"><paramref name="key"/> is null.</exception>
		public bool ContainsKey( TKey key )
		{
			WeakReference<TValue> valueRef;
			if( !_dictionary.TryGetValue( key, out valueRef ) )
				return false;

			TValue value;
			if( !valueRef.TryGetTarget( out value ) )
			{
				// doesn't exist anymore, remove
				_dictionary.Remove( key );
				return false;
			}

			return true;
		}

		/// <summary>
		/// Adds an element with the provided key and value to the <see cref="T:System.Collections.Generic.IDictionary`2"/>.
		/// </summary>
		/// <param name="key">The object to use as the key of the element to add.</param><param name="value">The object to use as the value of the element to add.</param><exception cref="T:System.ArgumentNullException"><paramref name="key"/> is null.</exception><exception cref="T:System.ArgumentException">An element with the same key already exists in the <see cref="T:System.Collections.Generic.IDictionary`2"/>.</exception><exception cref="T:System.NotSupportedException">The <see cref="T:System.Collections.Generic.IDictionary`2"/> is read-only.</exception>
		public void Add( TKey key, TValue value )
		{
			// Contract.Requires<ArgumentNullException>( value != null );
			if( value == null )
				throw new ArgumentNullException( "value" );

			WeakReference<TValue> valueRef;
			if( !_dictionary.TryGetValue( key, out valueRef ) )
			{
				// key does not exist, so we can safely add
				_dictionary.Add( key, new WeakReference<TValue>( value ) );
			}
			else
			{
				// key exists, but value might be disposed off already
				TValue currentValue;
				if( valueRef.TryGetTarget( out currentValue ) )
					// duplicate key
					throw new ArgumentException( "An element with the same key already exists" );

				// set to new value
				valueRef.SetTarget( value );
			}
		}

		/// <summary>
		/// Removes the element with the specified key from the <see cref="T:System.Collections.Generic.IDictionary`2"/>.
		/// </summary>
		/// <returns>
		/// true if the element is successfully removed; otherwise, false.  This method also returns false if <paramref name="key"/> was not found in the original <see cref="T:System.Collections.Generic.IDictionary`2"/>.
		/// </returns>
		/// <param name="key">The key of the element to remove.</param><exception cref="T:System.ArgumentNullException"><paramref name="key"/> is null.</exception><exception cref="T:System.NotSupportedException">The <see cref="T:System.Collections.Generic.IDictionary`2"/> is read-only.</exception>
		public bool Remove( TKey key )
		{
			WeakReference<TValue> valueRef;
			if( !_dictionary.TryGetValue( key, out valueRef ) )
			{
				// key does not exist, so we can safely add
				return false;
			}
			else
			{
				// key exists, but value might be disposed off already
				TValue value;
				if( valueRef.TryGetTarget( out value ) )
				{
					// exists, so return true
					_dictionary.Remove( key );
					return true;
				}

				// does not exist anymore, so return false
				_dictionary.Remove( key );
				return false;
			}
		}

		/// <summary>
		/// Gets the value associated with the specified key.
		/// </summary>
		/// <returns>
		/// true if the object that implements <see cref="T:System.Collections.Generic.IDictionary`2"/> contains an element with the specified key; otherwise, false.
		/// </returns>
		/// <param name="key">The key whose value to get.</param><param name="value">When this method returns, the value associated with the specified key, if the key is found; otherwise, the default value for the type of the <paramref name="value"/> parameter. This parameter is passed uninitialized.</param><exception cref="T:System.ArgumentNullException"><paramref name="key"/> is null.</exception>
		public bool TryGetValue( TKey key, out TValue value )
		{
			WeakReference<TValue> valueRef;
			if( !_dictionary.TryGetValue( key, out valueRef ) )
			{
				// key does not exist, so return false;
				value = null;
				return false;
			}
			else
			{
				return valueRef.TryGetTarget( out value );
			}
		}

		/// <summary>
		/// Gets or sets the element with the specified key.
		/// </summary>
		/// <returns>
		/// The element with the specified key.
		/// </returns>
		/// <param name="key">The key of the element to get or set.</param><exception cref="T:System.ArgumentNullException"><paramref name="key"/> is null.</exception><exception cref="T:System.Collections.Generic.KeyNotFoundException">The property is retrieved and <paramref name="key"/> is not found.</exception><exception cref="T:System.NotSupportedException">The property is set and the <see cref="T:System.Collections.Generic.IDictionary`2"/> is read-only.</exception>
		public TValue this[TKey key]
		{
			get
			{
				TValue value;
				if( TryGetValue( key, out value ) )
					return value;
				throw new KeyNotFoundException();
			}
			set
			{
				WeakReference<TValue> weakRef;
				if( _dictionary.TryGetValue( key, out weakRef ) )
					weakRef.SetTarget( value );
				else
					_dictionary.Add( key, new WeakReference<TValue>( value ) );
			}
		}

		/// <summary>
		/// Gets an <see cref="T:System.Collections.Generic.ICollection`1"/> containing the keys of the <see cref="T:System.Collections.Generic.IDictionary`2"/>.
		/// </summary>
		/// <returns>
		/// An <see cref="T:System.Collections.Generic.ICollection`1"/> containing the keys of the object that implements <see cref="T:System.Collections.Generic.IDictionary`2"/>.
		/// </returns>
		ICollection<TKey> IDictionary<TKey, TValue>.Keys
		{
			get
			{
				return (
					from kv in this
					select kv.Key
				).ToArray();
			}
		}

		/// <summary>
		/// Gets an <see cref="T:System.Collections.Generic.ICollection`1"/> containing the values in the <see cref="T:System.Collections.Generic.IDictionary`2"/>.
		/// </summary>
		/// <returns>
		/// An <see cref="T:System.Collections.Generic.ICollection`1"/> containing the values in the object that implements <see cref="T:System.Collections.Generic.IDictionary`2"/>.
		/// </returns>
		ICollection<TValue> IDictionary<TKey, TValue>.Values
		{
			get
			{
				return (
				  from kv in this
				  select kv.Value
				).ToArray();
			}
		}

		#endregion
	}
}
